package com.quktzhuanka.app.fragments;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.activity.JdDetailsActivity;
import com.quktzhuanka.app.adapter.JDAdapterList;
import com.quktzhuanka.app.base.BaseLazyFragment;
import com.quktzhuanka.app.bean.JdGoodsResp;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.utils.DrawableCenterTextView;
import com.quktzhuanka.app.utils.UIUtils;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;
/**
 * @属性:京东多商品页
 * @开发者:wmm
 * @时间:2018/12-07 11:36
 */
public class JdFragment extends BaseLazyFragment {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.right_icon)
    ImageView rightIcon;
    @BindView(R.id.jiage_st)
    DrawableCenterTextView jiageSt;
    @BindView(R.id.xiaoliang_st)
    DrawableCenterTextView xiaoliangSt;
    @BindView(R.id.yongjin_st)
    DrawableCenterTextView yongjinSt;
    @BindView(R.id.tuiguang_st)
    DrawableCenterTextView tuiguangSt;
    private JDAdapterList shopRecyclerAdapter;
    private String pid, usId;

    List<JdGoodsResp> taobaoGuesChildtBeans = new ArrayList<>();
    private int indexNum = 1;
    private GridLayoutManager linearLayoutManager;
    private boolean hasdata = true;
    Gson gson = new Gson();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            shopRecyclerAdapter.notifyDataSetChanged();
            super.handleMessage(msg);
        }
    };
    private TextView[] textViews;
    private String sort = "";
    private String sort_gz = "desc";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pdd, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        addListener();
        return view;
    }

    private void init() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            pid = arguments.getString("pid");
            usId = arguments.getString("us_id");
        }
        yongjinSt.setText("奖");
        tuiguangSt.setVisibility(View.GONE);
        textViews = new TextView[]{jiageSt, xiaoliangSt, yongjinSt};
        shopRecyclerAdapter = new JDAdapterList(getActivity(), R.layout.item_jd, taobaoGuesChildtBeans);
        linearLayoutManager = new GridLayoutManager(getActivity(), 1);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(shopRecyclerAdapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int screenMeasuredHeight = UIUtils.getScreenMeasuredHeight(getActivity());
                if (getScollYDistance() >= (screenMeasuredHeight / 2)) {
                    rightIcon.setVisibility(View.VISIBLE);
                } else {
                    rightIcon.setVisibility(View.GONE);
                }
            }
        });
    }

    private void addListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (hasdata) {
                    indexNum++;
                    getTbkListRequst();
                } else {
                    showToast("没有更多数据了");
                    refreshLayout.finishLoadMore(1000);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                indexNum = 1;
                hasdata = true;
                getTbkListRequst();
            }
        });
        //点击进入详情
        shopRecyclerAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                JdGoodsResp taobaoGuesChildtBean = taobaoGuesChildtBeans.get(position);
                if (taobaoGuesChildtBean != null) {
                    Intent intent = new Intent(context, JdDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goods", taobaoGuesChildtBean);
                    intent.putExtra("goods", bundle);
                    startActivity(intent);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * @属性:获取屏幕高度的方法
     * @开发者:田哥哥
     * @时间:2018/8/7 14:22
     */
    public long getScollYDistance() {
        int position = linearLayoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = linearLayoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void lazyload() { //懒加载，界面开始后刷新
        //开始刷新
        refreshLayout.autoRefresh();
    }

    /**
     * @属性:获取京东商品列表
     * @开发者:wmm
     * @时间:2018/12/2607 11:50
     */
    private void getTbkListRequst() {
        String SERVER_URL = "http://api-gw.haojingke.com/index.php/v1/api/jd/goodslist";
        RequestParams params = new RequestParams();
        params.put("apikey",Constants.jd_hjk_appikey);
        params.put("pageindex",indexNum);
        params.put("pagesize",10);
        params.put("ishot",0);
        params.put("owner","p");
        params.put("sortname",sort);
        params.put("sort",sort_gz);
        params.put("sortname",sort);
        params.put("isCoupon",1);
        params.put("mincommission",5);
        if (usId.equals("4") || usId.equals("5") || usId.equals("6")) {
            params.put("cid2",Long.valueOf(pid));
        } else if (!usId.equals("0")) {
            params.put("cid1",Long.valueOf(pid));
        } else {
            params.put("ishot",1);
            params.put("cid1",Long.valueOf(pid));
        }
        HttpUtils.post(SERVER_URL, params, new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject datas = new JSONObject(responseString);
                    if(datas.optInt("status_code") == 200){
                        final JSONArray list = datas.getJSONObject("data").getJSONArray("data");

                        if (indexNum == 1) {
                            taobaoGuesChildtBeans.clear();
                            if(refreshLayout!=null)
                            refreshLayout.finishRefresh();
                        } else {
                            if(refreshLayout!=null)
                                refreshLayout.finishLoadMore();
                        }
                        if (list.length() == 0) {
                            hasdata = false;
                            return;
                        }
                        int length = list.length();
                        for (int i = 0; i < length; i++) {
                            taobaoGuesChildtBeans.add(gson.fromJson(list.get(i).toString(), JdGoodsResp.class));
                        }
                        handler.sendEmptyMessage(0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });




//        String appKey = Constants.jdappKey;
//        String appSecret = Constants.jdclient_secret;
//        String accessToken = "";
//        final JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
//        final UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
//        final GoodsReq goodsReq = new GoodsReq();
//        goodsReq.setPageSize(6);            // 每页数量
//        goodsReq.setPageIndex(indexNum);    // 默认页数 1
//        goodsReq.setIsCoupon(1);            // 是否是优惠券商品，1：有优惠券，0：无优惠券
//        goodsReq.setIsHot(0);               // 是否是爆款，1：爆款商品，0：非爆款商品
//        goodsReq.setOwner("p");             // 商品类型：自营[g]，POP[p]
//        goodsReq.setSortName(sort);         // 排序字段(price：单价, commissionShare：佣金比例, commission：佣金， inOrderCount30Days：30天引单量， inOrderComm30Days：30天支出佣金)
//        goodsReq.setSort(sort_gz);          // asc,desc升降序,默认降序
//        goodsReq.setPricefrom(30.0);        // 商品价格下限
//        if (usId.equals("4") || usId.equals("5") || usId.equals("6")) {
//            goodsReq.setCid2(Long.valueOf(pid));
//        } else if (!usId.equals("0")) {
//            goodsReq.setCid1(Long.valueOf(pid));
//        } else {
////            goodsReq.setIsHot(1);
//            goodsReq.setCid1(Long.valueOf(pid));
//        }
//        request.setGoodsReqDTO(goodsReq);
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    UnionOpenGoodsQueryResponse response = client.execute(request);
//                    if (indexNum == 1) {
//                        taobaoGuesChildtBeans.clear();
//                        if(refreshLayout!=null)
//                        refreshLayout.finishRefresh();
//                    } else {
//                        if(refreshLayout!=null)
//                            refreshLayout.finishLoadMore();
//                    }
//                    if (response.getData() == null) {
//                        hasdata = false;
//                        return;
//                    }
//                    if (response.getData().length <= 0) {
//                        hasdata = false;
//                    }
//                    int length = response.getData().length;
//                    for (int i = 0; i < length; i++) {
//                        taobaoGuesChildtBeans.add(response.getData()[i]);
//                    }
//                    handler.sendEmptyMessage(0);
//                } catch (JdException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }

    @OnClick({R.id.right_icon, R.id.jiage_st, R.id.xiaoliang_st, R.id.yongjin_st})
    public void onViewClicked(View view) { //回到头部
        switch (view.getId()) {
            case R.id.right_icon:
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.smoothScrollToPosition(0);
                    }
                });
                break;
            case R.id.xiaoliang_st: //销量
                if ("desc".equals(sort_gz)) {
                    Drawable nav_up=getResources().getDrawable(R.mipmap.sort_select);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    xiaoliangSt.setCompoundDrawables(null, null, nav_up, null);
                    sort_gz = "asc";
                } else {
                    Drawable nav_bo=getResources().getDrawable(R.mipmap.sort_normal);
                    nav_bo.setBounds(0, 0, nav_bo.getMinimumWidth(), nav_bo.getMinimumHeight());
                    xiaoliangSt.setCompoundDrawables(null, null, nav_bo, null);
                    sort_gz = "desc";
                }
                sort = "4";
                refreshLayout.autoRefresh();
                selectView(1);
                break;
            case R.id.jiage_st: //价格
                if ("desc".equals(sort_gz)) {
                    Drawable nav_up=getResources().getDrawable(R.mipmap.sort_select);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    jiageSt.setCompoundDrawables(null, null, nav_up, null);
                    sort_gz = "asc";
                } else {
                    Drawable nav_bo=getResources().getDrawable(R.mipmap.sort_normal);
                    nav_bo.setBounds(0, 0, nav_bo.getMinimumWidth(), nav_bo.getMinimumHeight());
                    jiageSt.setCompoundDrawables(null, null, nav_bo, null);
                    sort_gz = "desc";
                }
                sort = "1";
                refreshLayout.autoRefresh();
                selectView(0);
                break;
            case R.id.yongjin_st: //奖
                if ("desc".equals(sort_gz)) {
                    Drawable nav_up=getResources().getDrawable(R.mipmap.sort_select);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    yongjinSt.setCompoundDrawables(null, null, nav_up, null);
                    sort_gz = "asc";
                } else {
                    Drawable nav_bo=getResources().getDrawable(R.mipmap.sort_normal);
                    nav_bo.setBounds(0, 0, nav_bo.getMinimumWidth(), nav_bo.getMinimumHeight());
                    yongjinSt.setCompoundDrawables(null, null, nav_bo, null);
                    sort_gz = "desc";
                }
                sort = "3";
                refreshLayout.autoRefresh();
                selectView(2);
                break;
        }
    }

    private void selectView(int position) {
        for (TextView textView : textViews) {
            textView.setTextColor(getResources().getColor(R.color.black));
        }
        textViews[position].setTextColor(getResources().getColor(R.color.gold));
    }

}
